import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

// import 'package:crimaster/model/user_model.dart';
// import 'package:crimaster/page/login/login_page.dart';
import 'package:flutter/material.dart';

import 'package:flutter/cupertino.dart';
// import 'package:crimaster/model/Login_user_model.dart';
import 'package:flutter/services.dart';
// import 'package:crimaster/utils/shared_key.dart';

// import 'navigator_utils.dart';
// import 'package:flutter/src/material/constants.dart';
// import 'package:flutter_native_image/flutter_native_image.dart';
// import 'package:flutter_absolute_path/flutter_absolute_path.dart';
// import 'package:heic_to_jpg/heic_to_jpg.dart';
// import 'package:multi_image_picker/multi_image_picker.dart';


class Utils {

  // static LoginUser loginUser;

  // static Future<LoginUser> checkUser() async {
  //   if (loginUser != null) {
  //     return loginUser;
  //   }
  //
  //   LoginUser user = await getUserData();
  //
  //   if (user != null) {
  //     loginUser = user;
  //     return user;
  //   }
  //
  //   return null;
  // }
  ///value: 文本内容；fontSize : 文字的大小；fontWeight：文字权重；maxWidth：文本框的最大宽度；maxLines：文本支持最大多少行 ；locale：当前手机语言；textScaleFactor：手机系统可以设置字体大小（默认1.0）
  static int offsetNovelText(String value, double fontSize, Size size,) {

    TextPainter textPainter = TextPainter(
      text:TextSpan(text:value ,style: TextStyle(fontSize: fontSize,color: Colors.black54)),
      textDirection: TextDirection.ltr,
    );

    textPainter.layout(maxWidth: size.width);

//    textPainter.paint(canvas, Offset(5,5));

    TextPosition textPosition = textPainter.getPositionForOffset(Offset(size.width, size.height-fontSize));


    return textPosition.offset;

  }
  static formDayTimeStr(String time) {
    time = time
        .split(' ')
        .last;
    return time;
  }

  static formatTimeStr(String time) {
    time = time.replaceAll('T', " ");
    time = time.replaceAll('Z', "");
    time = time.substring(0, 16);

    return time;
  }

  static formTimeStr(String time) {
    time = time.replaceAll('T', " ");
    time = time.replaceAll('Z', "");
    time = time.substring(5, 16);

    return time;
  }


  static formTimeBetweenDays(String time) {
    var timestampT = DateTime
        .parse(time)
        .millisecondsSinceEpoch;

    var now = new DateTime.now();

    var timestamp = now.millisecondsSinceEpoch;

    int between = (timestamp / 1000 - timestampT / 1000).ceil();

    return (between / 86400).round();
  }


//  判断时间差是否小于一分钟
  static checkLessThenMinute(String time,String fromTime) {
    var timestampT = DateTime
        .parse(time)
        .millisecondsSinceEpoch;

    var timestamp = DateTime
        .parse(fromTime)
        .millisecondsSinceEpoch;

    int between = (timestamp / 1000 - timestampT / 1000).ceil();

    print("fromTime===${fromTime}===${time}====${between/60}");
    if (between/60 < 3) {
//      三分钟
      return true;
    }
    return false;
  }


  static chatTimeformTimeBetweenStr(String time) {
    var timestampT = DateTime
        .parse(time)
        .millisecondsSinceEpoch;

    var now = new DateTime.now();

    var timestamp = now.millisecondsSinceEpoch;

    int between = (timestamp / 1000 - timestampT / 1000).ceil();


    if (between < 60) {
      return "刚刚";
    } else if (between < 600) {
      return "${(between / 60).ceil()}分钟前";
    } else {
      return formatTimeStr(time);
    }
  }

  static formTimeBetweenStr(String time) {
    var timestampT = DateTime
        .parse(time)
        .millisecondsSinceEpoch;

    var now = new DateTime.now();

    var timestamp = now.millisecondsSinceEpoch;

    int between = (timestamp / 1000 - timestampT / 1000).ceil();


    if (between < 60) {
      return "刚刚";
    } else if (between < 3600) {
      return "${(between / 60).ceil()}分钟前";
    } else if (between < 86400) {
      return "${(between / 3600).ceil()}小时前";
    } else {
      return "${(between / 86400).ceil()}天前";
    }
  }


  static checkTimeLessMonth(String time) {
    var timestampT = DateTime
        .parse(time)
        .millisecondsSinceEpoch;

    var now = new DateTime.now();

    var timestamp = now.millisecondsSinceEpoch;

    int between = (timestamp / 1000 - timestampT / 1000).ceil();

    var count =  between/3600/24;

    print("count=${between}=${count}");

    return count<1?true:false;
  }



  static formTimeBetweenTimeStr(String time, int days) {
    var timestampT = DateTime
        .parse(time)
        .millisecondsSinceEpoch;

    var now = new DateTime.now();

    var timestamp = now.millisecondsSinceEpoch;

    int between = (timestamp / 1000 - timestampT / 1000).ceil();

    between = days * 86400 - between;

    var t = "";
    int day = (between / 86400).toInt();
    if (day > 0) {
      t = '${day}' + '天';
      between -= day * 86400;
    }

    int hour = (between / 3600).toInt();
    if (hour > 0) {
      t = t + '${hour}' + '小时';
      between -= hour * 3600;
    }

    int min = (between / 60).toInt();
    if (min > 0) {
      t = t + '${min}' + '分钟';
      between -= min * 600;
    }

    return t;
  }


  // static Future<LoginUser> saveUserData(Map data) async {
  //   UserModel userModel = UserModel.fromJson(data);
  //
  //   LoginUser user = await getUserData();
  //   user.user = userModel;
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   prefs.setString(SharedKey.USER_KEY, user.toString());
  //
  //   loginUser = user;
  //
  //   return loginUser;
  // }
  //
  // static Future<LoginUser> getUserData() async {
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   String userStr = await prefs.getString(SharedKey.USER_KEY);
  //
  //   if (userStr != null) {
  //     LoginUser user = LoginUser.fromJson(json.decode(userStr));
  //     return user;
  //   } else {
  //     return null;
  //   }
  // }
  //
  //
  // static Future<bool> checkUserToLogin(BuildContext context) async {
  //   LoginUser user = await checkUser();
  //   if (user != null) {
  //     return true;
  //   } else {
  //     NavigatorUtil.showBottomPage(
  //         context,
  //         LoginPage(
  //           isShowCancelBtn: true,
  //           respond: (LoginUser user) {
  //             if (user != null) {
  //               loginUser = user;
  //               return true;
  //             }
  //             return false;
  //           },
  //         ));
  //   }
  // }
  //
  // static Future<LoginUser> checkGetUserToLogin(BuildContext context) async {
  //   LoginUser user = await checkUser();
  //   if (user != null) {
  //     return user;
  //   } else {
  //     NavigatorUtil.showBottomPage(
  //         context,
  //         LoginPage(
  //           isShowCancelBtn: true,
  //           respond: (LoginUser user) {
  //             if (user != null) {
  //               loginUser = user;
  //               return true;
  //             }
  //             return false;
  //           },
  //         ));
  //   }
  // }

  static getDayTimeStr(){
    DateTime dateTime= DateTime.now();
    return dateTime.toString().substring(0,10);
  }

  static getWidth(BuildContext context) {
    return MediaQuery
        .of(context)
        .size
        .width;
  }

  static getHeight(BuildContext context) {
    return MediaQuery
        .of(context)
        .size
        .height;
  }

  static getContentHeight(BuildContext context) {
    return MediaQuery
        .of(context)
        .size
        .height - kToolbarHeight;
  }



  static Uint8List hexStringToUint8List(String hexString) {
    List<int> byteList =
    List<int>.generate(
      hexString.length ~/ 2,
          (index) => int.parse(hexString.substring(index * 2, index * 2 + 2), radix: 16),
    );

     return Uint8List.fromList(byteList);
  }

  static  String listToHexString(List<int> bytes) {
    return bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join('');
  }



    static bool checkCmdResult(String hexString) {

    if(hexString.startsWith("A5")){
      return false;
    }


    return true;
  }






  Uint8List stringToUint8List(String command) {
    List<int> byteList = [];

    // 直接将整个命令字符串转换为ASCII码值
    for (int i = 0; i < command.length; i++) {
      if (command[i] == '<LF>') {
        byteList.add(0x0A); // 添加换行符的ASCII码
      } else if (command[i] == '<CR>') {
        byteList.add(0x0D); // 添加回车符的ASCII码
      } else {
        byteList.add(command.codeUnitAt(i)); // 其他字符直接添加ASCII码
      }
    }

    return Uint8List.fromList(byteList);
  }

  static int hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  static List<int> getBleLoraCommand(int target){

    String targetStr = target.toRadixString(16);
    //补零

    targetStr = targetStr.padLeft(4,'0');

    print("targetStr----${targetStr}");

    //高位
    int hint = hexToInt(targetStr.substring(0,2));
    //低位
    int lint = hexToInt(targetStr.substring(2,4));

    //命令和
    int sum = 8+hint+lint;

    String sumStr = sum.toRadixString(16);

    sumStr = sumStr.padLeft(4,'0');

    //高位
    int hSum = hexToInt(sumStr.substring(0,2));
    //低位
    int lSum = hexToInt(sumStr.substring(2,4));

    // A5 00 05 03 01 02 00 06
    List<int> writeDatas = [165,0,5,3,hint,lint,hSum,lSum];
    print(writeDatas);
    return writeDatas;
  }

  //  验证手机号
  static bool isPhone(String input) {
    RegExp mobile = new RegExp(r"1[0-9]\d{9}$");
    return mobile.hasMatch(input);
  }
  static bool isStartPoint(String input) {
    RegExp point = new RegExp(r"^[+-@=?.,!`'*/](.*?)");
    return point.hasMatch(input);
  }

  static bool isRepeatStr(String input) {
    RegExp repeat = new RegExp(r"([\d])\1{2}");
    RegExp repeat1 = new RegExp(r"([a-z])\1{2}");

    return repeat.hasMatch(input) || repeat1.hasMatch(input);
  }


  static bool haveNewVersion(String newVersion, String old) {
    if (newVersion == null || newVersion.isEmpty || old == null || old.isEmpty)
      return false;
    int newVersionInt, oldVersion;
    var newList = newVersion.split('.');
    var oldList = old.split('.');
    if (newList.length == 0 || oldList.length == 0) {
      return false;
    }
    for (int i = 0; i < newList.length; i++) {
      newVersionInt = int.parse(newList[i]);
      oldVersion = int.parse(oldList[i]);
      if (newVersionInt > oldVersion) {
        return true;
      } else if (newVersionInt < oldVersion) {
        return false;
      }
    }

    return false;
  }

//   static Future<MultipartFile> imgConversionIdentifier(Asset asset) async {
//
//     String filePath = await FlutterAbsolutePath.getAbsolutePath(asset.identifier);
//
//     print("filePath==${filePath}");
//     String jpegPath = filePath;
//     String filename = asset.name;
//
//     if(filePath.contains('HEIC') || filePath.contains('heic')){
//       jpegPath = await HeicToJpg.convert(filePath);
//       filename = filename.replaceAll('HEIC', "jpg");
//       filename = filename.replaceAll('heic', "jpg");
//     }
//
//     File compressedFile = await FlutterNativeImage.compressImage(jpegPath,quality: 60, percentage: 50);
//
//     Uint8List list = compressedFile.readAsBytesSync();
//
//     if(asset.originalHeight>3000 || asset.originalWidth>3000 || list.length>1048576){
//
//       compressedFile = await FlutterNativeImage.compressImage(jpegPath,quality: 50, percentage: 45);
//
//       list = compressedFile.readAsBytesSync();
//
//     }
//
//
//
//
// //    File compressedFile2 = await FlutterNativeImage.compressImage(jpegPath,quality: 60, percentage: 40);
// //
// //
// //    Uint8List list1 = compressedFile1.readAsBytesSync();
// //
// //    Uint8List list2 = compressedFile2.readAsBytesSync();
//
//
//
//
//     print("filePath1==${list.length}===${asset.originalHeight}====${asset.originalWidth}");
//
// //    if(list.length>){
// //
// //    }
//
//     ByteData byteData = list.buffer.asByteData();
//
//     List<int> imageData = byteData.buffer.asUint8List();
//
//     return MultipartFile.fromBytes(imageData, filename:filename);
//
//   }

//    以符号开头
//
//连续数字或字母
//
//手机号
//微信 QQ


//    以符号开头
//    /^[，?!`~,.''].+$/
//连续数字或字母
//    /([0-9a-zA-Z])\1{2}/
//手机号
//微信 QQ

}
